#!/bin/bash

# 指定时间段
start_time="0800"
end_time="1800"

# 指定程序的位置
path="/home/avs/release"

# 指定程序名
vcut="vlog-cut"
vcfg="camera.json"
vupload="vlog-upload.py"

# 获取当前时间
current_time=$(date "+%H%M")

function start_program(){
    if pgrep -f "$vcut" > /dev/null; then
        echo "${current_time} [start] $vcut is running, do nothing" >> $path/daemon.log
    else
        echo "${current_time} [start] $vcut is not running, run it" >> $path/daemon.log
        $path/$vcut $path/$vcfg > /dev/null 2>&1 &
    fi

    if pgrep -f "$vupload" > /dev/null; then
        echo "${current_time} [start] $vupload is running, do nothing" >> $path/daemon.log
    else
        echo "${current_time} [start] $vupload is not running, run it" >> $path/daemon.log
        python3 $path/$vupload > /dev/null 2>&1 &
    fi
}

function close_program(){
    if pgrep -f "$vcut" > /dev/null; then
        pid=$(pgrep -f "$vcut")
        kill ${pid}
        echo "${current_time} [close] $vcut is running, close it" >> $path/daemon.log
    else
        echo "${current_time} [close] $vcut is not running, do nothing" >> $path/daemon.log
    fi

    if pgrep -f "$vupload" > /dev/null; then
        pid=$(pgrep -f "$vupload")
        kill ${pid}
        echo "${current_time} [close] $vupload is running, close it" >> $path/daemon.log
    else
        echo "${current_time} [close] $vupload is not running, do nothing" >> $path/daemon.log
    fi
}

# 根据时间段决定启动程序还是关闭程序
if [[ ${start_time}<=${current_time} && ${current_time}<=${end_time} ]]; then
    start_program
else
    close_program
fi